﻿namespace Reap.AzureResource.API
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Web.Http.Dependencies;

	using Ninject;
	using Ninject.Activation;
	using Ninject.Parameters;
	using Ninject.Syntax;

	public class NinjectResolver : NinjectScope, IDependencyResolver
	{
		#region Fields

		private readonly IKernel kernel;

		#endregion

		#region Constructors and Destructors

		public NinjectResolver(IKernel kernel)
			: base(kernel)
		{
			this.kernel = kernel;
		}

		#endregion

		#region Public Methods and Operators

		public IDependencyScope BeginScope()
		{
			return new NinjectScope(this.kernel.BeginBlock());
		}

		#endregion
	}

	public class NinjectScope : IDependencyScope
	{
		#region Fields

		protected IResolutionRoot ResolutionRoot;

		#endregion

		#region Constructors and Destructors

		public NinjectScope(IResolutionRoot kernel)
		{
			this.ResolutionRoot = kernel;
		}

		#endregion

		#region Public Methods and Operators

		public void Dispose()
		{
			var disposable = (IDisposable)this.ResolutionRoot;
			if (disposable != null)
			{
				disposable.Dispose();
			}
			this.ResolutionRoot = null;
		}

		public object GetService(Type serviceType)
		{
			IRequest request = this.ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
			return this.ResolutionRoot.Resolve(request).SingleOrDefault();
		}

		public IEnumerable<object> GetServices(Type serviceType)
		{
			IRequest request = this.ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
			return this.ResolutionRoot.Resolve(request).ToList();
		}

		#endregion
	}
}